<template>
  <div>
    <div style="height: 200px">
      <FormPanel ref="formPanel" :cols="2" :labelWidth="110" :list="formList" :formType="type" :isSubmitBtn="false" style="margin-top: 20px" @formChange="formChangeHandle" />
      <div style="margin-left: 110px">备注：默认短信签名为"回复TD退订【】"</div>
    </div>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button v-if="type !== 'show'" type="primary" @click="saveDialog">{{ btnText }}</el-button>
    </div>
  </div>
</template>
<script>
import { addTemplate, editTemplate, queryCareTypes } from '@/api/customerRepair/visitRules/SMSTemplate2';
import { dictionary } from '@/utils/dictMixin';
import { mapActions, mapState } from 'vuex';
import moment from 'moment';

export default {
  name: 'SMSPanel',
  components: {},
  mixins: [dictionary],
  props: {
    recordVersion: String,
    smsTemplateId: String,
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    this.saveData = null;
    return {
      formList: this.createFormList(),
      codeList: []
    };
  },
  computed: {
    btnText() {
      return this.conf[this.type];
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.type === 'edit') {
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
      this.initCodeList();
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '模板类型',
          fieldName: 'smsTemplateType',
          placeholder: '请选择',
          itemList: this.createDictList('1572'),
          change: val => {
            this.changeTempateName(val);
          }
        },
        {
          type: 'INPUT',
          label: '模板名称',
          fieldName: 'smsTemplateName',
          placeholder: '模板名称',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否默认',
          fieldName: 'isDefault',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '数据来源',
          disabled: true,
          fieldName: 'dataSources',
          placeholder: '请选择',
          initialValue: 10451001,
          itemList: this.createDictList('1045')
        },
        {
          type: 'SELECT',
          label: '可用变量',
          fieldName: 'value1',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.changeVariable(val);
          }
        },
        {
          type: 'TEXT_AREA',
          label: '模板内容',
          selfCols: 2,
          fieldName: 'templateContent',
          placeholder: '模板内容',
          initialValue: ''
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    closeDialog(type) {
      this.$emit('close', false, type);
    },
    filterDict(codeStr, dict) {
      let dictList = this.createDictList(dict);
      let res = [];
      for (let i = 0; i < dictList.length; i++) {
        if (codeStr.indexOf(dictList[i].value) != -1) {
          res.push(dictList[i]);
        }
      }
      return res;
    },
    dictFormat(dict) {
      if (dict && dict != '') {
        let dictList = this.createDictList(1591);
        for (let i = 0; i < dictList.length; i++) {
          if (dict === dictList[i].text) {
            return dictList[i].value;
          }
        }
      }
    },
    templateFormat(template) {
      if (template !== '') {
        var reg = new RegExp('\\{\\[[^(\\s|\\})]+\\]\\}', 'g');
        var reg2 = new RegExp('[^\\{\\[\\]\\}]+', 'g');
        var matchResult = template.match(reg);
        if (!matchResult) {
          return template;
        }
        var matchKeys;
        for (let i = 0; i < matchResult.length; i++) {
          var result = matchResult[i].match(reg2);
          var val = this.dictFormat(result[0]);
          if (val || val == '') {
            matchKeys = matchKeys == undefined ? {} : matchKeys;
            matchKeys[result] = '{[' + val + ']}';
          }
        }
        for (var key in matchKeys) {
          var reg3 = new RegExp('(\\{\\[' + key + '\\]\\})', 'g');
          template = template.replace(reg3, matchKeys[key]);
        }
        return template;
      } else {
        return this;
      }
    },
    async changeVariable(val) {
      val = this.createDictText(val, 1591);
      if (val && '' != val) {
        this.formList[5].initialValue = this.formList[5].initialValue + '{[' + val + ']}';
      }
    },
    async initCodeList() {
      const res = await queryCareTypes();
      if (res.resultCode == 200) {
        this.codeList = res.data;
        if (this.rowData.smsTemplateType && this.rowData.smsTemplateType != '') {
          for (let i = 0; i < this.codeList.length; i++) {
            if (this.codeList[i].careTypeCode === this.rowData.smsTemplateType) {
              let data = this.filterDict(this.codeList[i].careTypeRelationInVO.smsVariables, '1591');
              this.formList[4].itemList = data;
            }
          }
        }
      } else {
        this.$message.error('获取答案信息失败');
        return;
      }
    },
    async changeTempateName(val) {
      this.formList[5].initialValue = '';
      for (let i = 0; i < this.codeList.length; i++) {
        if (this.codeList[i].careTypeCode === val) {
          let data = this.filterDict(this.codeList[i].careTypeRelationInVO.smsVariables, '1591');
          this.formList[4].itemList = data;
        }
      }
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData !== null) {
        let res = {};
        this.saveData.smsTemplateContent = this.templateFormat(this.saveData.templateContent);
        if (this.type === 'add') {
          res = await addTemplate(this.saveData);
        }
        if (this.type === 'edit') {
          this.saveData.smsTemplateId = this.smsTemplateId;
          this.saveData.recordVersion = this.recordVersion;
          res = await editTemplate(this.saveData);
        }

        if (res.resultCode === 200) {
          this.closeDialog('refresh');
        } else {
          this.$message(`${res.errMsg}`);
        }
      }
    }
  }
};
</script>
